17. Unknown Breed

Unknown Breed

Question:

For our last update, you’ll be fixing another odd behavior in the UI. The list looks a little funny when there is an unknown breed. There is just a blank space in the list item, below the pet name.

Instead of leaving it blank, a better user experience would be to display the phrase “Unknown breed” in the list item if there is no breed.
The app should look like this when you’re done with this step:

Note that this is purely a UI change in the CatalogActivity. The text “Unknown breed” should not be saved in the database. If you open up the pet in the editor, the breed field should be blank:

Start Quiz:

Solution:

Solution Code.

First and foremost, since we’re adding the string “Unknown breed” let’s save that in the strings.xml file.

<!-- Label for the pet's breed if the breed is unknown [CHAR LIMIT=20] -->
<string name="unknown_breed">Unknown breed</string>

Next, we move to the PetCursorAdapter.java file. when we’re displaying the pet in the CatalogActivity, we’ll check whether there is a breed or not using the TextUtils.isEmpty method. If there is no breed, then we set the TextView in the list item to show “Unknown breed”

In PetCursorAdapter.java:

/**
 * This method binds the pet data (in the current row pointed to by cursor) to the given
 * list item layout. For example, the name for the current pet can be set on the name TextView
 * in the list item layout.
 *
 * @param view    Existing view, returned earlier by newView() method
 * @param context app context
 * @param cursor  The cursor from which to get the data. The cursor is already moved to the
 *                correct row.
 */
@Override
public void bindView(View view, Context context, Cursor cursor) {
    // Find individual views that we want to modify in the list item layout
    TextView nameTextView = (TextView) view.findViewById(R.id.name);
    TextView summaryTextView = (TextView) view.findViewById(R.id.summary);

    // Find the columns of pet attributes that we're interested in
    int nameColumnIndex = cursor.getColumnIndex(PetEntry.COLUMN_PET_NAME);
    int breedColumnIndex = cursor.getColumnIndex(PetEntry.COLUMN_PET_BREED);

    // Read the pet attributes from the Cursor for the current pet
    String petName = cursor.getString(nameColumnIndex);
    String petBreed = cursor.getString(breedColumnIndex);

    // If the pet breed is empty string or null, then use some default text
    // that says "Unknown breed", so the TextView isn't blank.
    if (TextUtils.isEmpty(petBreed)) {
        petBreed = context.getString(R.string.unknown_breed);
    }

    // Update the TextViews with the attributes for the current pet
    nameTextView.setText(petName);
    summaryTextView.setText(petBreed);
}

INSTRUCTOR NOTE:

Hint: TextUtils.isEmpty(String s) returns true if the input String is null or empty.